package com.bacsumu.boogservice.dao;

import java.util.Collection;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jdo.support.JdoDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
 
import com.bacsumu.boogservice.entity.HelloWorld;
import com.google.appengine.api.datastore.Key;

@Repository
@Transactional(readOnly = false)
public class HelloWorldJdoDaoImpl extends JdoDaoSupport implements HelloWorldDao{
	
	@Autowired
	public HelloWorldJdoDaoImpl(PersistenceManagerFactory pmf)
	{
		setPersistenceManagerFactory(pmf);
	}
	
	@Override
	 public Key create(final HelloWorld greeting) {
	  getJdoTemplate().makePersistent(greeting);
	  return greeting.getKey();
	 }
	 
	 @Override
	 public Collection<HelloWorld> getAllGreetings(final int selectedPage) {
	 
	  final PersistenceManager pm = getPersistenceManager();
	   
	  try {
	 
	   final Query query = pm.newQuery(HelloWorld.class);
	   query.setOrdering("date descending");
	    
	   @SuppressWarnings("unchecked")
	   final Collection<HelloWorld> greetings =
	    (Collection<HelloWorld>) query.execute();
	    
	   return pm.detachCopyAll((Collection<HelloWorld>)greetings);
	  }
	   
	  finally {
	   releasePersistenceManager(pm);
	  }
	 
	 }
}
